package com.kongjs.online.preview.utils;

import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

public class MediaTypeUtils {
    private static final String MIME_TYPES_FILE_NAME = "mime.types";
    private static final MultiValueMap<String, MediaType> fileExtensionToMediaTypes = parseMimeTypes();

    public static MultiValueMap<String, MediaType> parseMimeTypes() {
        InputStream is = ClassLoader.getSystemResourceAsStream(MIME_TYPES_FILE_NAME);
        Assert.state(is != null, MIME_TYPES_FILE_NAME + " not found in classpath");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.US_ASCII))) {
            MultiValueMap<String, MediaType> result = new LinkedMultiValueMap<>();
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.isEmpty() || line.charAt(0) == '#') {
                    continue;
                }
                String[] tokens = StringUtils.tokenizeToStringArray(line, " \t\n\r\f");
                MediaType mediaType = MediaType.parseMediaType(tokens[0]);
                for (int i = 1; i < tokens.length; i++) {
                    String fileExtension = tokens[i].toLowerCase(Locale.ENGLISH);
                    result.add(fileExtension, mediaType);
                }
            }
            return result;
        } catch (IOException ex) {
            throw new IllegalStateException("Could not read " + MIME_TYPES_FILE_NAME, ex);
        }
    }

    public static List<MediaType> getMediaTypes(@Nullable String filename) {
        List<MediaType> mediaTypes = null;
        String ext = StringUtils.getFilenameExtension(filename);
        if (ext != null) {
            mediaTypes = fileExtensionToMediaTypes.get(ext.toLowerCase(Locale.ENGLISH));
        }
        return (mediaTypes != null ? mediaTypes : Collections.emptyList());
    }

    public static Optional<MediaType> getMediaType(@Nullable String filename) {
        return getMediaTypes(filename).stream().findFirst();
    }
}
